<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input clearable placeholder="单位名称" v-model="queryForm.unitName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item style="float: right">
      <el-button @click="addOrUpdateHandle()" type="primary" v-if="isAuth('tra:unit:save')">新增</el-button>
       <!-- <el-button :disabled="dataListSelections.length <= 0" @click="deleteHandle()" type="danger"
                   v-if="isAuth('tra:unit:delete')">批量删除
        </el-button>-->
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      :header-cell-style="{background:'#F5F7FA',color:'#606266'}"
      show-summary
      :summary-method="getSummaries"
      style="width: 100%;"
      v-loading="dataListLoading">
      <!--<el-table-column
        align="center"
        header-align="center"
        type="selection"
        width="50">
      </el-table-column>-->
      <el-table-column
        align="center"
        header-align="center"
        label="单位名称"
        prop="name">
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        label="办公室主任"
        prop="officeChiefName">
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        label="电话"
        prop="officeChiefNum">
      </el-table-column>
      <el-table-column
        align="center"
        header-align="center"
        label="二维码"
        prop="qrCodeUrl">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover">
            <img :src="'https://www.ycbg.vip/' + scope.row.qrCodeUrl" alt="图片不存在"/>
            <img slot="reference" :src="'https://www.ycbg.vip/' + scope.row.qrCodeUrl" :alt="scope.row.picture"
                 style="max-height: 50px;max-width: 130px">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        prop="totalMember"
        header-align="center"
        align="center"
        label="会员总数">
      </el-table-column>
      <el-table-column
        prop="totalStay"
        header-align="center"
        align="center"
        label="总入住房间数">
      </el-table-column>
      <el-table-column
        prop="totalPrice"
        header-align="center"
        align="center"
        label="总金额">
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        width="100"
        label="创建时间">
      </el-table-column>
      <el-table-column
        align="center"
        fixed="right"
        header-align="center"
        label="操作"
        width="150">
        <template slot-scope="scope">
          <el-button @click="addOrUpdateHandle(scope.row.id)" icon="el-icon-edit" size="small" type="primary" plain>修改
          </el-button>
          <!--          <el-button @click="deleteHandle(scope.row.id)" size="small" type="danger" plain>删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="pageIndex"
      :page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="totalPage"
      @current-change="currentChangeHandle"
      @size-change="sizeChangeHandle"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update @refreshDataList="getDataList" ref="addOrUpdate" v-if="addOrUpdateVisible"></add-or-update>
  </div>
</template>

<script>
  import AddOrUpdate from './unit-add-or-update'
  import {getToken} from '@/utils/auth'

  export default {
    data () {
      return {
        dataForm: {
          key: '',
          startDate: ''
        },
        queryForm: {
          unitName: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        fileList: [],
        totalMeb: '',
        totalPrice: '',
        totalStay: '',
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        importExcelVisible: false,
        uploadAction: window.SITE_CONFIG.baseUrl + '/tra/unit/importExcel'
      }
    },
    computed: {
      headers: function () {
        return {'token': getToken()}
      }
    },
    components: {
      AddOrUpdate
    },
    activated () {
      this.getDataList()
    },
    methods: {
      handleRemove (file, fileList) {
        // console.log(file, fileList)
      },
      handlePreview (file) {
        // console.log(file)
      },
      handleExceed (files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      handleSuccess (response, file) {
        if (response.code === 0) {
          this.fileList = null
          this.$notify({
            title: '成功',
            message: file.name + '上传成功！',
            type: 'success'
          })
          this.getDataList()
        }
      },
      handleError (err, file) {
        this.$notify.error({
          title: '失败',
          message: err + '上传失败！'
        })
      },
      exportExcel () {
        this.$http({
          url: this.$http.adornUrl('/tra/unit/exportExcel'),
          method: 'get',
          responseType: 'blob'
        }).then(function (res) {
          let filename = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1])
          this.fileDownload(res.data, filename)
          this.$notify({
            title: '成功',
            message: '导出成功！',
            type: 'success'
          })
        }.bind(this)).catch((error) => {
          this.$notify.error({
            title: '失败',
            message: error + '导出失败！'
          })
        })
      },
      fileDownload (data, fileName) {
        let blob = new Blob([data], {
          type: 'application/octet-stream'
        })
        let filename = fileName
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // 解决IE不能导出
          window.navigator.msSaveBlob(blob, this.queryForm.date2 + filename + '.xlsx')
        } else {
          const blobUrl = window.URL.createObjectURL(new Blob([blob]))
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = blobUrl
          link.setAttribute('download', filename + '.xlsx')
          if (typeof link.download === 'undefined') {
            link.setAttribute('target', '_blank')
          }
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(blobUrl)
        }
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/tra/unit/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'unitName': this.queryForm.unitName
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
            this.totalMeb = data.list.totalMeb
            this.totalPrice = data.list.totalPrice
            this.totalStay = data.list.totalStay
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      /* deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/tra/unit/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      }, */
      getSummaries (param) {
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '统 计'
            return
          }
          if (index === 4) {
            sums[index] = this.totalMeb + '人'
            return
          }
          if (index === 5) {
            sums[index] = this.totalStay + '间'
            return
          }
          if (index === 6) {
            sums[index] = this.totalPrice + '元'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
          } else {
            sums[index] = ''
          }
        })
        return sums
      }

    }
  }
</script>
